package com.sjyy.common.interceptor;

import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.sjyy.common.util.AuthorityUtil;
import com.sjyy.vo.sessionmodel.SessionUser;
import com.sjyy.common.authority.RaAuthority;
import com.sjyy.common.authority.enums.AuthorityTypeEnum;
import com.sjyy.common.authority.enums.ResultTypeEnum;

public class AuthorityAnnotationInterceptor extends HandlerInterceptorAdapter {

	final Logger logger = LoggerFactory.getLogger(getClass());

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

		if(handler instanceof org.springframework.web.servlet.resource.ResourceHttpRequestHandler){
			// TODO 静态文件
			return true;
		}
		HandlerMethod handler2=(HandlerMethod) handler;
		RaAuthority raAuthority = handler2.getMethodAnnotation(RaAuthority.class);

		if(null == raAuthority){
			return true;
		}

		logger.debug("raAuthority", raAuthority.toString());

//		HttpSession session = request.getSession();
//		SessionUser user = (SessionUser)session.getAttribute("login");
//		boolean aflag = false;
//
//		for(AuthorityTypeEnum at:raAuthority.authorityTypes()){
//			if(AuthorityUtil.hasAuthority(at.getIndex(), user.getProperties())==true){
//				aflag = true;
//				break;
//			}
//		}
//
//		if(false == aflag){
//
//			if (raAuthority.resultType() == ResultTypeEnum.page) {
//				StringBuilder sb = new StringBuilder();
//				sb.append(request.getContextPath());
//				sb.append("/commons/error.jsp?detail_system_error_msg=").append(URLEncoder.encode("没有权限","utf-8"));
//				response.sendRedirect(sb.toString());
//			} else if (raAuthority.resultType() == ResultTypeEnum.json) {
//				response.setCharacterEncoding("utf-8");
//				response.setContentType("text/html;charset=UTF-8");
//				OutputStream out = response.getOutputStream();
//				PrintWriter pw = new PrintWriter(new OutputStreamWriter(out,"utf-8"));
//				pw.println("{\"result\":false,\"resultcode\":-1,\"msg\":\"没有权限\"}");
//				pw.flush();
//				pw.close();
//			}
//
//			return false;
//		}

		return true;
	}

}